<?php

namespace app\admin\model;

use think\db\exception\DbException;
use think\Model;
use think\model\relation\HasOne;

/**
 * UserCardOrder
 * @controllerUrl 'userCardOrder'
 */
class UserCardOrder extends Model
{
    // 表名
    protected $name = 'user_card_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = false;

    protected $type = [
        'pay_time' => 'timestamp:Y-m-d H:i:s',
    ];


    public function getUserIdAttr($value, $row)
    {
        return !$value ? '' : $value;
    }

    public function category()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 获取唯一订单号
     * @return string
     * @throws DbException
     */
    public function getOrderSn(): string
    {
        try {
            [$micro, $time] = explode(' ', microtime());
            $micro = explode('.', sprintf('%.6f', $micro));
            $micro = $micro[1];
        } catch (\Exception $e) {
            $micro = rand(100000, 999999);
        }
        $orderSn = date('YmdHis') . $micro . rand(1000, 9999);
        $hasSn = $this->where('order_sn', $orderSn)->count();
        if ($hasSn > 0) {
            return $this->getOrderSn();
        }
        return $orderSn;
    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }
}